layui.use(['table', 'form', 'layer', 'laydate'], function () {
    var table = layui.table,
        form = layui.form,
        layer = layui.layer,
        laydate = layui.laydate,
        $ = layui.jquery;

    // 初始化日期范围选择器
    laydate.render({
        elem: '#packingDateRange',
        type: 'date',
        range: true
    });

    // 初始化表格
    var tableIns = table.render({
        elem: '#dataTable',
        url: '/Packing/GetPagedList',
        method: 'post',
        contentType: 'application/json',
        headers: {
            "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()
        },
        page: true,
        limit: 10,
        limits: [10, 20, 50, 100],
        cols: [[
            { type: 'checkbox', fixed: 'left' },
            { field: 'id', title: 'ID', width: 80, hide: true },
            { field: 'packingCode', title: '装箱单编号', width: 150 },
            { field: 'packingDate', title: '装箱日期', width: 120, templet: function(d) {
                return d.packingDate ? layui.util.toDateString(new Date(d.packingDate), 'yyyy-MM-dd') : '';
            }},
            { field: 'saleOrderCode', title: '销售订单编号', width: 150 },
            { field: 'invoiceCode', title: '发票编号', width: 150 },
            { field: 'customerCode', title: '客户编码', width: 120 },
            { field: 'customerName', title: '客户名称', width: 180 },
            { field: 'packingLength', title: '箱长度', width: 100 },
            { field: 'packingWidth', title: '箱宽度', width: 100 },
            { field: 'packingHeight', title: '箱高度', width: 100 },
            { field: 'packingSize', title: '尺寸单位', width: 100 },
            { field: 'netWeight', title: '净重', width: 100 },
            { field: 'grossWeight', title: '毛重', width: 100 },
            { field: 'unitWeight', title: '重量单位', width: 100 },
            { field: 'inspector', title: '检查员', width: 120 },
            { 
                field: 'state', 
                title: '状态', 
                width: 100,
                templet: function(d) {
                    var states = {
                        0: '<span class="status-tag status-0">草稿</span>',
                        1: '<span class="status-tag status-1">已确认</span>',
                        2: '<span class="status-tag status-2">已完成</span>',
                        3: '<span class="status-tag status-3">已取消</span>'
                    };
                    return states[d.state] || '';
                }
            },
            {
                title: '操作',
                width: 150,
                fixed: 'right',
                toolbar: '#operationBar'
            }
        ]],
        request: {
            pageName: 'pageNumber',
            limitName: 'pageSize'
        },
        where: {},
        done: function(res) {
            // 只有当请求确实失败时才显示错误提示
            if (!res.code && !res.success && res.msg) {
                layer.msg(res.msg, {icon: 2});
            }
        },
        parseData: function(res) {
            // 如果后端返回的是标准的 APIResult 格式
            if (res.success === true && res.data) {
                return {
                    "code": 0, // 数据正常
                    "msg": "",
                    "count": res.data.totalCount,
                    "data": res.data.items || []
                };
            } 
            // 如果后端返回的是错误信息
            else if (res.success === false) {
                return {
                    "code": 1, // 数据异常
                    "msg": res.message || "获取数据失败",
                    "count": 0,
                    "data": []
                };
            }
            // 如果返回的数据格式完全不符合预期
            else {
                return {
                    "code": 1,
                    "msg": "数据格式错误",
                    "count": 0,
                    "data": []
                };
            }
        }
    });

    // 监听工具条
    table.on('tool(dataTable)', function (obj) {
        var data = obj.data;
        if (obj.event === 'edit') {
            // 打开编辑页面
            layer.open({
                type: 2,
                title: '编辑装箱单',
                area: ['100%', '100%'],
                content: '/Packing/Edit?id=' + data.id,
                maxmin: true
            });
        } else if (obj.event === 'del') {
            deletePacking(data.id);
        }
    });

    // 监听表格复选框选择
    table.on('checkbox(dataTable)', function (obj) {
        var checkStatus = table.checkStatus('dataTable');
        $('#batchDeleteBtn').css('display', checkStatus.data.length > 0 ? 'inline-block' : 'none');
    });

    // 监听搜索按钮点击
    form.on('submit(searchForm)', function (data) {
        var searchData = data.field;
        
        // 处理日期范围
        if (searchData.packingDateRange) {
            var dates = searchData.packingDateRange.split(' - ');
            if (dates.length === 2) {
                searchData.startPackingDate = dates[0];
                searchData.endPackingDate = dates[1];
            }
            delete searchData.packingDateRange;
        }

        // 处理状态值
        if (searchData.state === '') {
            delete searchData.state;
        } else {
            searchData.state = parseInt(searchData.state);
        }

        tableIns.reload({
            where: JSON.stringify(searchData),
            page: {
                curr: 1
            }
        });
        return false;
    });

    // 监听重置按钮点击
    $('#resetBtn').click(function () {
        $('#searchForm')[0].reset();
        form.render();
        tableIns.reload({
            where: {},
            page: {
                curr: 1
            }
        });
    });

    // 监听新增按钮点击
    $('#addBtn').click(function () {
        // 打开新增页面
        layer.open({
            type: 2,
            title: '新增装箱单',
            area: ['100%', '100%'],
            content: '/Packing/Create',
            maxmin: true
        });
    });

    // 监听批量删除按钮点击
    $('#batchDeleteBtn').click(function () {
        var checkStatus = table.checkStatus('dataTable');
        if (checkStatus.data.length === 0) {
            layer.msg('请选择要删除的记录');
            return;
        }

        var ids = checkStatus.data.map(function (item) {
            return item.id;
        });
        batchDeletePacking(ids);
    });

    // 删除装箱记录
    function deletePacking(id, callback) {
        layer.confirm('确定要删除这条记录吗？', {icon: 3, title: '提示'}, function(index) {
            $.ajax({
                url: '/Packing/Delete',
                type: 'POST',
                data: { id: id },
                success: function(res) {
                    if (res.success) {
                        layer.msg('删除成功', {icon: 1});
                        if (callback) callback();
                        tableIns.reload();
                    } else {
                        layer.msg(res.message || '删除失败', {icon: 2});
                    }
                },
                error: function() {
                    layer.msg('服务器错误，请稍后重试', {icon: 2});
                }
            });
            layer.close(index);
        });
    }

    // 批量删除装箱记录
    function batchDeletePacking(ids, callback) {
        if (!ids || ids.length === 0) {
            layer.msg('请选择要删除的记录', {icon: 2});
            return;
        }

        layer.confirm('确定要删除选中的 ' + ids.length + ' 条记录吗？', {icon: 3, title: '提示'}, function(index) {
            $.ajax({
                url: '/Packing/BatchDelete',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(ids),
                success: function(res) {
                    if (res.success) {
                        layer.msg('批量删除成功', {icon: 1});
                        if (callback) callback();
                        tableIns.reload();
                        $('#batchDeleteBtn').hide();
                    } else {
                        layer.msg(res.message || '批量删除失败', {icon: 2});
                    }
                },
                error: function() {
                    layer.msg('服务器错误，请稍后重试', {icon: 2});
                }
            });
            layer.close(index);
        });
    }

    // 自动生成编号
    window.autoGenerateCode = function () {
        var date = new Date();
        var year = date.getFullYear();
        var month = (date.getMonth() + 1).toString().padStart(2, '0');
        var day = date.getDate().toString().padStart(2, '0');
        var random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
        var code = 'PACK' + year + month + day + random;
        $('#packingCodeInput').val(code);
    };

    // 选择客户
    window.selectCustomer = function () {
        layer.msg('请实现客户选择功能');
    };
}); 